package com.huahai.api.aliyunai.sub;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;
import com.huahai.api.aliyunai.model.CreateOutPaintingTaskRequest;
import com.huahai.api.aliyunai.model.CreateOutPaintingTaskResponse;
import com.huahai.api.aliyunai.model.GetOutPaintingTaskResponse;
import com.huahai.exception.BusinessException;
import com.huahai.exception.ErrorCode;
import com.huahai.util.ThrowUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * 阿里云百炼 AI API 接口
 * @author huahai
 */
@Slf4j
@Component
public class ALiYunAIApi {

    // 读取阿里云百炼 AI API 密钥
    @Value("${aliYunAi.apikey}")
    private String apikey;

    // 创建任务地址
    public static final String CREATE_OUT_PAINTING_TASK_URL = "https://dashscope.aliyuncs.com/api/v1/services/aigc/image2image/out-painting";

    // 查询任务状态
    public static final String GET_OUT_PAINTING_TASK_URL = "https://dashscope.aliyuncs.com/api/v1/tasks/%s";

    /**
     * 创建 AI 扩图任务
     * @param createOutPaintingTaskRequest 创建任务参数
     * @return 创建任务结果
     */
    public CreateOutPaintingTaskResponse createOutPaintingTask(CreateOutPaintingTaskRequest createOutPaintingTaskRequest){
        // 1. 校验参数
        ThrowUtils.throwIf(createOutPaintingTaskRequest == null, ErrorCode.OPERATION_ERROR, "扩图参数为空");
        // 2. 发送请求
        //curl --location --request POST 'https://dashscope.aliyuncs.com/api/v1/services/aigc/image2image/out-painting' \
        //--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
        //--header 'X-DashScope-Async: enable' \
        //--header 'Content-Type: application/json' \
        //--data '{}'
        HttpRequest httpRequest = HttpRequest.post(CREATE_OUT_PAINTING_TASK_URL)
                .header("Authorization", "Bearer " + apikey)
                // 启用异步模式 （关键）
                .header("X-DashScope-Async", "enable")
                .header("Content-Type", "application/json")
                .body(JSONUtil.toJsonStr(createOutPaintingTaskRequest));
        // 3. 解析响应的结果
        // java7 支持try-with-resources 自动关闭流
        try(HttpResponse httpResponse = httpRequest.execute()) {
            // 判断响应状态码
            if(!httpResponse.isOk()){
                log.error("创建任务失败：{}", httpResponse.body());
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "AI 扩图失败");
            }
            // 解析响应结果
            CreateOutPaintingTaskResponse taskResponse = JSONUtil.toBean(httpResponse.body(), CreateOutPaintingTaskResponse.class);
            // 判断响应code
            String code = taskResponse.getCode();
            if(StrUtil.isNotBlank(code)){
                String errorMessage = taskResponse.getMessage();
                log.error("AI 扩图失败，errorCode:{}, errorMessage:{}", code, errorMessage);
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "AI 扩图接口响应异常");
            }
            // 4. 返回结果
            return taskResponse;
        }
    }

    /**
     * 查询任务状态
     * @param taskId 任务ID
     * @return 任务状态响应类
     */
    public GetOutPaintingTaskResponse getOutPaintingTask(String taskId){
        // 1. 校验参数
        ThrowUtils.throwIf(StrUtil.isBlank(taskId), ErrorCode.OPERATION_ERROR, "任务 ID 为空");
        // 2. 发送请求
        HttpRequest httpRequest = HttpRequest.get(String.format(GET_OUT_PAINTING_TASK_URL, taskId))
                .header(Header.AUTHORIZATION, "Bearer " + apikey);
        // 3. 解析响应的结果
        try(HttpResponse httpResponse = httpRequest.execute()) {
            if(!httpResponse.isOk()){
                log.error("查询任务状态失败：{}", httpResponse.body());
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "查询任务状态失败");
            }
            // 4. 返回结果
            return JSONUtil.toBean(httpResponse.body(), GetOutPaintingTaskResponse.class);
        }
    }
}
